<template>
  <div>
    <el-container style="height: 900px; border: 1px solid #eee">
      <!-- 顶部导航栏 -->
      <el-header style="font-size: 40px; background-color: rgb(238, 241, 246)">
        <div class="header-left">
          <span>书缘校园-校园二手书交流系统</span>
        </div>
        <div class="header-right">
          <router-link to="/mySetting">
            <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
          </router-link>
        </div>
      </el-header>

      <el-container>
        <!-- 侧边栏 -->
        <aside-layout></aside-layout>

        <!-- 主内容区 -->
        <el-main>
          <!-- 设置选项卡 -->
          <el-tabs v-model="activeTab" type="card">
            <el-tab-pane label="个人资料" name="profile">
              <el-card class="profile-card">
                <div slot="header" class="clearfix">
                  <span>个人资料</span>
                </div>
                <el-form :model="profileForm" :rules="profileRules" ref="profileForm" label-width="100px">
                  <el-form-item label="头像">
                    <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/"
                      :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                      <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" />
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-form-item>
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="profileForm.nickname" placeholder="请输入昵称"></el-input>
                  </el-form-item>
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="profileForm.email" placeholder="请输入邮箱"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="submitProfileForm">保存</el-button>
                    <el-button @click="resetProfileForm('profileForm')">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-tab-pane>

            <el-tab-pane label="账号安全" name="security">
              <el-card class="security-card">
                <div slot="header" class="clearfix">
                  <span>账号安全</span>
                </div>
                <el-form :model="securityForm" :rules="securityRules" ref="securityForm" label-width="100px">
                  <el-form-item label="旧密码" prop="oldPassword">
                    <el-input type="password" v-model="securityForm.oldPassword" placeholder="请输入旧密码"></el-input>
                  </el-form-item>
                  <el-form-item label="新密码" prop="newPassword">
                    <el-input type="password" v-model="securityForm.newPassword" placeholder="请输入新密码"></el-input>
                  </el-form-item>
                  <el-form-item label="确认新密码" prop="confirmPassword">
                    <el-input type="password" v-model="securityForm.confirmPassword" placeholder="请再次输入新密码"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="submitSecurityForm">保存</el-button>
                    <el-button @click="resetSecurityForm('securityForm')">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-tab-pane>

            <el-tab-pane label="通知设置" name="notifications">
              <el-card class="notifications-card">
                <div slot="header" class="clearfix">
                  <span>通知设置</span>
                </div>
                <el-form :model="notificationForm" ref="notificationForm" label-width="100px">
                  <el-form-item label="邮件通知">
                    <el-switch v-model="notificationForm.emailNotification"></el-switch>
                  </el-form-item>
                  <el-form-item label="短信通知">
                    <el-switch v-model="notificationForm.smsNotification"></el-switch>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="submitNotificationForm">保存</el-button>
                    <el-button @click="resetNotificationForm">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-tab-pane>
          </el-tabs>

          <!-- 退出按钮 -->
          <div class="logout-container">
            <el-button type="danger" @click="logout">退出当前账号</el-button>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import AsideLayout from '../../layout/AsideLayout.vue';
import axios from 'axios'; // 引入 axios

export default {
  components: { AsideLayout },
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.securityForm.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };
    return {
      activeTab: 'profile', // 当前激活的选项卡
      profileForm: {
        avatar: '', // 初始化为空，从后端获取
        nickname: '', // 初始化为空，从后端获取
        email: '', // 初始化为空，从后端获取
      },
      profileRules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      securityForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      securityRules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      notificationForm: {
        emailNotification: false, // 初始化为 false，从 localStorage 中获取
        smsNotification: false // 初始化为 false，从 localStorage 中获取
      }
    };
  },
  created() {
    this.fetchProfileData(); // 组件加载时获取个人资料
    this.fetchNotificationSettings(); // 组件加载时获取通知设置
  },
  methods: {
    // 获取个人资料
    async fetchProfileData() {
      try {
        // 从 localStorage 中获取用户ID
        const userId = localStorage.getItem('userId');

        if (!userId) {
          throw new Error('用户ID未找到');
        }

        const response = await axios.get(`http://localhost:3000/api/setting/profile/${userId}`);
        const { username, email } = response.data;

        // 更新表单数据
        this.profileForm = {
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png', // 假设头像固定
          nickname: username,
          email: email,
        };
      } catch (error) {
        console.error('获取个人资料失败:', error);
        this.$message.error('获取个人资料失败，请重试');
      }
    },
    // 获取通知设置
    fetchNotificationSettings() {
      const settings = localStorage.getItem('notificationSettings');
      if (settings) {
        this.notificationForm = JSON.parse(settings);
      }
    },
    // 保存通知设置
    submitNotificationForm() {
      localStorage.setItem('notificationSettings', JSON.stringify(this.notificationForm));
      this.$message.success('通知设置保存成功');
    },
    // 重置通知设置
    resetNotificationForm() {
      this.notificationForm = {
        emailNotification: false,
        smsNotification: false,
      };
      localStorage.removeItem('notificationSettings');
      this.$message.success('通知设置已重置');
    },
    handleAvatarSuccess(res, file) {
      this.profileForm.avatar = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    async submitProfileForm() {
      try {
        this.$refs.profileForm.validate(async (valid) => {
          if (valid) {
            // 从 localStorage 中获取用户ID
            const userId = localStorage.getItem('userId');

            if (!userId) {
              throw new Error('用户ID未找到');
            }

            const { nickname, email } = this.profileForm;

            // 调用后端API更新个人资料
            const response = await axios.put(`http://localhost:3000/api/setting/profile/${userId}`, {
              nickname,
              email,
            });

            this.$message.success(response.data.message);
          } else {
            this.$message.error('表单验证失败');
            return false;
          }
        });
      } catch (error) {
        console.error('更新个人资料失败:', error);
        this.$message.error('更新个人资料失败，请重试');
      }
    },
    resetProfileForm(formName) {
      this.$refs[formName].resetFields();
    },
    async submitSecurityForm() {
      try {
        // 表单验证
        this.$refs.securityForm.validate(async (valid) => {
          if (valid) {
            // 从 localStorage 中获取用户ID
            const userId = localStorage.getItem('userId');

            if (!userId) {
              this.$message.error('用户ID未找到，请重新登录');
              return;
            }

            const { oldPassword, newPassword } = this.securityForm;

            // 调用后端API修改密码
            const response = await axios.put(`http://localhost:3000/api/setting/security/${userId}`, {
              oldPassword,
              newPassword,
            });

            this.$message.success(response.data.message);
          } else {
            this.$message.error('表单验证失败');
            return false;
          }
        });
      } catch (error) {
        console.error('修改密码失败:', error);
        this.$message.error('修改密码失败，请重试');
      }
    },
    resetSecurityForm(formName) {
      this.$refs[formName].resetFields();
    },
    logout() {
      // 退出逻辑
      this.$message.success('退出成功');
      this.$router.push('/'); // 跳转到首页
    }
  }
};
</script>

<style scoped>
.el-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  font-weight: bold;
}

.header-right {
  display: flex;
  align-items: center;
}

.profile-card,
.security-card,
.notifications-card {
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.logout-container {
  margin-top: 20px;
  text-align: center;
}
</style>